import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {ComponentClass} from 'react'
import {AtSwitch, AtIcon} from 'taro-ui'
import {Image, Input, Text, View} from '@tarojs/components'
import {CityLocation, DefaultInfo} from '../utils/server.interface'
import {http} from '../utils/http'
import {
  MOVIE_CREATE,
  RESOURCE_URL,
  STORAGE_TEMP_DATA,
  GET_DEFAULT_INFO,
  MOVIE_ORDERCREATE,
  PC_ORDER_STATUS,
  PC_MOVIE_QRCODE
} from '../constants/api'
import {payment} from "../utils/payment.service";
import {GetRequest, getTempSellerId} from "../utils/tools";
import {h5Wx} from "../utils/h5.service";
import GzhAuth from "../components/gzh-auth/gzh-auth"
import {newHttp} from "../utils/request";
import './Morder.scss'

type PageStateProps = {
  location: CityLocation
}
type PageDispatchProps = {}
type PageOwnProps = {}
type PageState = {
  orderInfo: any
  agree: boolean
  agreeAni: boolean
  orderNum: string
  checkList: any
  movie: any
  open: boolean
  phoneNum: string
  make: boolean
  info: any
  env: string
  pcqrcode: string
  pcQrcodeShow: boolean
  tempSellerId: any
}
type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface Morder {
  props: IProps
}

class Morder extends Component {
  state: PageState = {
    orderInfo: {},
    agree: false,
    agreeAni: false,
    orderNum: '',
    checkList: [],
    movie: {},
    open: true,
    phoneNum: '',
    make: true,
    info: {},
    env: '',
    pcqrcode: '',
    tempSellerId: '',
    pcQrcodeShow: false
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    const orderNum = Taro.getCurrentInstance().router.params.orderNum
    if (!orderNum) {
      Taro.navigateBack({
        delta: 1
      })
    }
    const tempSellerId = getTempSellerId(this)
    this.setState({tempSellerId})
    const res = await http.postCar(MOVIE_CREATE, {orderNum, tempSellerId})
    const checkList = Taro.getStorageSync("checkList")
    const query: any = Taro.getCurrentInstance().router.params;
    let movie: any = null;
    if (query.env == 'pc') {
      const result = await http.HPost(STORAGE_TEMP_DATA, {type: 0});
      console.log(result);
      if (result.data) {
        movie = JSON.parse(result.data);
      }
    } else {
      movie = Taro.getStorageSync("seats")
    }
    this.setState({orderNum, checkList, movie, info: res})
  }

  async componentDidShow() {
    const userInfo = await http.post<DefaultInfo>(GET_DEFAULT_INFO, {})
    if (userInfo) {
      this.setState({phoneNum: userInfo.phone || ''})
    }
    this.setState({env: Taro.getCurrentInstance().router.params.env})
  }

  agreeOk() {
    const agree = this.state.agree
    this.setState({
      agree: !agree,
      agreeAni: false
    })
  }

  async sureBuy() {
    const {agree, orderNum, make, movie, phoneNum, checkList, info, tempSellerId} = this.state
    const data = {
      tempSellerId,
      planId: movie.plan_id,
      orderNum
    }
    if (!agree) {
      Taro.showToast({
        title: '请阅读相关协议',
        icon: 'none'
      })
      return false;
    }
    const r = /^1[0-9]{10}$/;　　//1开头0-9内十位数
    if (!r.test(phoneNum)) {
      Taro.showToast({title: '手机号码格式不正确', icon: 'none'})
      return false
    }
    const seatsAry = []
    const seatPrice = []
    const seatName = []
    checkList.map(item => {
      seatsAry.push(item.seat_id)
      seatPrice.push(info.userPrice)
      seatName.push(item.seat_name)
    })
    data['seatId'] = seatsAry.join("|")
    data['seatPrice'] = seatPrice.join("|")
    data['seatName'] = seatName.join("|")

    data['mobile'] = phoneNum
    data['make'] = make
    data['referSellerId'] = Taro.getStorageSync('bindSellerId') || 0
    Taro.showLoading({
      title: '正在为您出票'
    })
    if (this.state.env == 'pc') {
      if (process.env.TARO_ENV === 'h5') {
        data['paySource'] = 'gongzhonghao'
        data['rout'] = 'pc'
      }
      const result = await newHttp.post(MOVIE_ORDERCREATE, data);
      if (result) {
        const pcQrode = await newHttp.catchGet(PC_MOVIE_QRCODE + data.orderNum, data);
        Taro.hideLoading();
        this.setState({pcqrcode: pcQrode, pcQrcodeShow: true})
        const time = setInterval(async () => {
          const status = await newHttp.catchGet(PC_ORDER_STATUS + data.orderNum)
          if (status.isPay) {
            clearInterval(time)
            Taro.redirectTo({url: '/main/order/success?env' + Taro.getCurrentInstance().router.params.env + '&pay=' + (Number(info.userPrice) * checkList.length).toFixed(2)})
          }
        }, 1000)
      }
    } else {
      const result = await payment.moviePay(data)
      Taro.hideLoading()
      if (result) {
        Taro.redirectTo({url: '/main/order/success?pay=' + (Number(info.userPrice) * checkList.length).toFixed(2)})
      }
    }

  }

  phone(e) {
    this.setState({
      phoneNum: e.detail.value
    })

  }

  goOnBuy() {
    const {agree} = this.state
    if (agree) {
      this.offBuy()
    } else {
      Taro.showToast({title: '请阅读并接受以上规则', icon: 'none'})
    }
    this.setState({agreeAni: false}, () => {
      this.setState({agreeAni: true})
    })
  }

  look() {
    this.setState({
      open: true
    })
  }

  offBuy() {
    this.setState({
      open: false
    })
  }

  makeSeats(make) {
    this.setState({
      make
    })
  }

  render() {
    const {pcQrcodeShow, pcqrcode, agree, agreeAni, checkList, movie, open, make, info, phoneNum} = this.state
    return (
      <View className='movieOrder'>
        <GzhAuth />
        <View className='info-box'>
          <View className='info-content'>
            <Image className='info-img' src={RESOURCE_URL + movie.poster} mode='aspectFill'></Image>
            <View className='info-info'>
              <View className='info-name'>{movie.movieName}<Text>{checkList.length}张</Text></View>
              <View className='info-time-buy'>{movie.start_time}（{movie.copyLanguage}{movie.plan_type}）</View>
              <View className='info-add-buy'>{info.cinemaName}</View>
              <View
                className='info-hall-buy'
              >{movie.hallName} {checkList && checkList.length > 0 && checkList.map((item, index) =>
                <Text key={index}><Text className='red'></Text>{item.seatName}</Text>
              )}</View>
            </View>
          </View>
          <View className='info-xuzhi' onClick={this.look.bind(this)}>
            <View className='info-xuzhi-lable'><AtIcon customStyle='margin-right:5px' prefixClass='car'
              value='iconjingshi' size='12'
              color='#ff524a'
            ></AtIcon>不支持退票</View>
            <View className='info-xuzhi-btn'>须知 <AtIcon value='chevron-right' size='14' color='#fff'></AtIcon></View>
          </View>
        </View>
        <View className='order'>
          <View className='order-price'>
            <Text>市场价</Text>
            <Text>￥{info.marketPrice}/张</Text>
          </View>
          {(Number(info.marketPrice) - Number(info.userPrice)) > 0 &&
          <View className='order-youhui'>
            <Text>优惠</Text>
            <Text
              className='order-red'
            >-￥{(checkList.length * (Number(info.marketPrice) - Number(info.userPrice))).toFixed(2)}</Text>
          </View>}
          <View className='order-sum'>
            <Text>总计</Text>
            <Text className='order-red'>￥{(Number(info.userPrice) * checkList.length).toFixed(2)}</Text>
          </View>
          <View className='order-heng'></View>
          <View className='order-phone'>
            <Text>手机号 <Text className='order-red'>（必填）</Text></Text>
            <Input type='number' onInput={this.phone.bind(this)} value={phoneNum} placeholder='请输入手机号' />
          </View>
          <View className='order-tip'>手机号仅用于场次取消或异常情况时联系</View>
          <View className='order-heng'></View>
          <View className='order-pre'>
            <AtSwitch title='调剂座位' color='#b4f2c3' onChange={this.makeSeats.bind(this)} border={false} checked={make} />
          </View>
          <View className='order-tips'>
            <View>1.接受调座，当您选择的座位已出售时，自动为您选择最佳观影座位。</View>
            <View>2.若不接受调座则出票率较低，请谨慎选择。</View>
          </View>

        </View>
        <View className='agree'>
          <View onClick={this.agreeOk.bind(this)}><Image className='img'
            src={agree ? RESOURCE_URL + "/resources/weapp/images/xuan.png" : RESOURCE_URL + "/resources/weapp/images/weixuan.png"}
          ></Image>
            我已经查看并同意“产品购买须知”和</View><Text className='jump' onClick={this.look.bind(this)}>“服务条款”</Text>
        </View>
        <View className='bottom-buy'>
          <View className='bottom-buy-price'>
            ￥<Text>{(Number(info.userPrice) * checkList.length).toFixed(2)}</Text>
          </View>
          <View className='bottom-buy-sure' style={`color:${agree ? '#fff' : '#ffcb8d'}`}
            onClick={this.sureBuy.bind(this)}
          >确认支付</View>
        </View>
        {open && <View className='look-agree'>
          <View className='look-agree-bj' onClick={this.offBuy.bind(this)}></View>
          <View className='look-agree-con'>
            <View className='title'>退改签协议</View>
            <View className='text'>
              <View>点击同意本协议前,请务必审慎阅读、充分理解本协议中的服务条款。</View>
              <View>1、接受调座，当您选择的座位已出售时，自动为您选择最佳观影座位。</View>
              <View>2、已经出票的订单不可改签、退款。</View>
              <View>3、提前2小时购买，如订单出票失败，可重新下单。</View>
              <View>4、付款后1小时内出票，若未出票，系统会在3个工作日内原路退回至您购票时使用的支付账户。</View>
              <View>如有对本协议有任何疑问，可随时联系平台客服</View>
            </View>
            <View className={`agree-wow ${agreeAni ? 'animation-agree' : ''}`} onClick={this.agreeOk.bind(this)}><AtIcon
              className='icon' value='check-circle' size='15'
              color={agree ? '#ff961a' : '#e2e2e2'}
            ></AtIcon> 我已阅读并接受以上规则</View>
            <View className='agree-btn' style={`color:${agree ? '#fff' : '#ffcb8d'}`}
              onClick={this.goOnBuy.bind(this)}
            >继续购票</View>
          </View>
          <View className='off-buy' onClick={this.offBuy.bind(this)}>暂不购票</View>
        </View>}
        {pcQrcodeShow && <View className='curtainRoot'>
          <View className='pc-root'>
            <Image className='pcqrcode' src={pcqrcode} mode='widthFix'></Image>
            <View className='pc-tips'>请用微信扫码支付</View>
            <View onClick={() => {
              this.setState({pcQrcodeShow: false})
            }} className='gzh-close'
            >
              <AtIcon value='close' color='#000'></AtIcon>
            </View>
          </View>
        </View>}
      </View>
    )
  }
}

export default Morder as ComponentClass<PageOwnProps, PageState>
